<template>
  <div>
    <TopBar ref="topBar" :tabName="tabName" :backValue="backValue">
      <template #operate>
        <!-- <el-button :loading="loading" @click="cancel">取消</el-button> -->
        <el-button :loading="loading" type="primary" @click="save">确定</el-button>
      </template>
    </TopBar>
    <div class="myFormBox" v-loading="loading">
      <el-form :model="form" ref="formRef" label-width="100px">
        <FormTitle titleName="基础信息" style="margin-bottom: 16px;"></FormTitle>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠券名称" prop="name" :rules="getRules('input', '优惠劵名称')">
              <el-input style="width: 360px;" placeholder="请输入" v-model="form.name" show-word-limit
                :maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注名称" prop="remarksName">
              <el-input style="width: 360px;" placeholder="请输入" v-model="form.remarksName" show-word-limit
                :maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放总量" prop="totalAmountIssued" :rules="getRules('input', '发放总量')">
              <el-input style="width: 100px;" placeholder="请输入" v-model="form.totalAmountIssued"
               @input="()=>{form.totalAmountIssued=limitInt(form.totalAmountIssued)}"></el-input>
              <span style="margin-left: 8px;">张</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠金额" prop="discountAmount" :rules="getRules('input', '优惠金额')">
              <el-input style="width: 100px;" placeholder="请输入" v-model="form.discountAmount"
               @input="()=>{form.discountAmount=limitFloat(form.discountAmount)}"></el-input>
              <span style="margin-left: 8px;">元</span>
            </el-form-item>
          </el-col>
        </el-row>
        <FormTitle titleName="活动规则" style="margin-bottom: 16px;"></FormTitle>
        <el-row>
          <el-col :span="24">
            <el-form-item label="使用门槛" prop="serviceThreshold" :rules="getRules('input', '使用门槛')">
              <span>满</span>
              <el-input style="width: 100px;margin: 0 8px;" placeholder="请输入" v-model="form.serviceThreshold"
               @input="()=>{form.discountAmount=limitFloat(form.discountAmount)}"></el-input>
              <span>元可用</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="使用时间" prop="serviceTime" :rules="getRules('input', '使用时间')">
              <div class="serviceTime">
                <el-radio-group v-model="form.serviceTime" @change="serviceTimeChange">
                  <el-radio :label="0">
                    <el-form-item class="flex align-items-center" style="margin-bottom: 0px;" prop="serviceTimeValue"
                      :rules="form.serviceTime ? [] : serviceTimeRules">
                      <span style="margin-right: 8px;">指定时间</span>
                      <el-date-picker v-model="form.serviceTimeValue" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                        date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                    </el-form-item>
                  </el-radio>
                  <el-radio :label="1">
                    <el-form-item class="flex align-items-center" style="margin-bottom: 0px;" prop="serviceTimeValue1"
                      :rules="form.serviceTime ? serviceTimeRules : []">
                      <span>领取后</span>
                      <el-input placeholder="请输入" style="width: 100px;margin: 0 8px;" v-model="form.serviceTimeValue1"
                       @input="()=>{form.serviceTimeValue1=limitInt(form.serviceTimeValue1)}"></el-input>
                      <span>天后生效</span>
                    </el-form-item>
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动范围" prop="totalAmountIssued" :rules="getRules('select', '活动范围')">
              <div style="width: 100%;">
                <el-radio-group v-model="form.rangeActivity">
                  <el-radio :label="0">全部商品可用</el-radio>
                  <el-radio :label="1">指定商品可用</el-radio>
                  <el-radio :label="2">指定商品不可用</el-radio>
                </el-radio-group>
                <div style="margin-bottom: 8px;">
                  <el-button v-show="form.rangeActivity" @click="productSelectDialogOpen" plain type="primary">
                    <img class="btn-icon" :src="addIcon" alt="">
                    选择商品
                  </el-button>
                </div>
                <el-table :header-cell-style="{ background: '#ddd' }" v-show="form.rangeActivity" stripe
                  :data="listData" max-height="300" style="width: 100%;">
                  <el-table-column show-overflow-tooltip prop="productName" label="商品名称"></el-table-column>
                  <el-table-column label="供应商" prop="supplier"></el-table-column>
                  <el-table-column label="操作" width="120">
                    <template v-slot="{ row, $index }">
                      <el-button type="danger" plain @click="delProduct(row, $index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="myPagination">
                  <el-pagination
                    v-show="form.rangeActivity"
                    background
                    v-model:current-page="pageConfig.page"
                    v-model:page-size="pageConfig.pageSize"
                    :page-sizes="pageConfig.pageSizes"
                    :layout="pageConfig.layout"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <ProductSelectDialog :show="productSelectDialogShow" @close="productSelectDialogClose" />
  </div>
</template>

<script setup>
import { useManualPaging,useImportImg } from '@/hooks/index'
import { useTableData } from '../Hooks/index';
import { useAction } from '../Hooks/action.js'
import TopBar from '@/components/Topbar/index.vue';
import FormTitle from '@/components/Form/FormTitle.vue'
import ProductSelectDialog from '../Components/ProductSelectDialog.vue'
import getRules from '@/validUtils';
import { limitFloat,limitInt } from '@/utils/common.js'
const addIcon = useImportImg('btn-add-blue')

const { searchTable } = useTableData();
const route = useRoute();
const isEdit = computed(() => route.query.id ? true : false)
const tabName = computed(() => isEdit.value ? '编辑优惠券' : '新增优惠券')
const topBar = ref();
const backValue = '/wholesaleManagement/marketingManagement/couponManagement/couponManagementIndex'
const loading = ref(false)

const { rangeActivityList } = useAction()
const {
    pageConfig,
    listData,
    total,
    handleSizeChange,
    handleCurrentChange} = useManualPaging(rangeActivityList)

const formRef = ref(null)
const form = ref({
  couponName: '',
  remarksName: '',
  totalAmountIssued: null,
  discountAmount: null,
  serviceThreshold: null,
  serviceTime: 0,
  serviceTimeValue: null,
  serviceTimeValue1: null,
  rangeActivity: 0,
})
const serviceTimeRules = [{
  validator: (rule, value, callback) => {
    if (form.value.serviceTime === 0 && !form.value.serviceTimeValue) {
      callback(new Error('请选择时间'))
    } else if (form.value.serviceTime === 1 && !form.value.serviceTimeValue1) {
      callback(new Error('请输入天数'))
    } else {
      callback()
    }
  },
  trigger: 'blur'
}]
const serviceTimeChange = (val) => {
  if (val === 0) {
    formRef.value.clearValidate(['serviceTimeValue1'])
  } else {
    formRef.value.clearValidate(['serviceTimeValue'])
  }
}
const delProduct = (row, index) => {
  rangeActivityList.value.splice(index, 1)
}

const productSelectDialogShow = ref(false)
const productSelectDialogOpen = () => {
  productSelectDialogShow.value = true
}
const productSelectDialogClose = (val) => {
  productSelectDialogShow.value = false
}

const save = () => { 
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('form', form.value)
    }
  })
}
const cancel = () => {
  topBar.value.backHandle()
}
onActivated(() => {
  if (isEdit.value) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
    }, 1000)
  } else {
    // formRef.value.resetFields()
    // form.value = {
    //   couponName: '',
    //   remarksName: '',
    //   totalAmountIssued: null,
    //   discountAmount: null,
    //   serviceThreshold: null,
    //   serviceTime: 0,
    //   serviceTimeValue: null,
    //   serviceTimeValue1: null,
    //   rangeActivity: 0,
    // }
  }
})
</script>

<style lang="less" scoped>
.myFormBox {
  padding: 24px;

  .serviceTime {
    :deep(.el-radio-group) {
      flex-direction: column;
      gap: 16px;
      align-items: normal;
    }
  }
  .myPagination{
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
}
.btn-icon{
  width: 14px;
  height: 14px;
  margin-right: 4px;
}
</style>